package tgc.edu.library.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.library.custom.CommonService;
import tgc.edu.library.entity.Book;
import tgc.edu.library.repository.BookRepository;

@Service
public class BookService extends CommonService<Book, Integer>{
	@Autowired
	private BookRepository bookDAO;
	
	/** 图片存放位置 **/
	private final static String IMAGEPATH="d:\\jeecgs\\image";

	
	public boolean savefile(MultipartFile file, String uuid) {
		File path = path(file.getContentType());
		String filename = file.getOriginalFilename();
		Book picture = new Book();
		picture.setFilename(filename);
		picture.setUuid(uuid);
		String storeaddress = path.getAbsolutePath();
		picture.setStoreaddress(storeaddress);
		File saveFile = new File(path,uuid);
		try {
			bookDAO.save(picture);
			file.transferTo(saveFile);
			return true;
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			return false;
		}
	}


	private File path(String contentType) {
		File pat=new File("d:\\jeecgs");
		File path=new File(BookService.IMAGEPATH);
		if(!pat.isDirectory()) {
			pat.mkdir();
		}
		if(!path.isDirectory()) {
			path.mkdir();
		}
		return path;
	}


	public Book findByUuid(String uuid) {
		return bookDAO.findByUuid(uuid);
	}


	/**
	 * 下载
	 * @param request
	 * @param fileName
	 * @return
	 */
	public void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
		Book fileentity = bookDAO.findByUuid(uuid);
		String filename = fileentity.getFilename();
		filename = getStr(request, filename);
		File file = new File(fileentity.getStoreaddress(), uuid);
		if(file.exists()) {
			FileInputStream fis;
			try {
				fis = new FileInputStream(file);
				response.setContentType("application/x-msdownload");
				response.addHeader("Content-Disposition", "attachment; filename=" + filename );
				ServletOutputStream out = response.getOutputStream();
				byte[] buf=new byte[2048];
				int n=0;
				while((n=fis.read(buf))!=-1){
					out.write(buf, 0, n);
				}
				fis.close();
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	private String getStr(HttpServletRequest request, String filename) {
		String downloadFileName = null;
		//仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表 *=utf-8'zh_cn'文件名.xx部分）
        String agent = request.getHeader("USER-AGENT");  
         try {
            	 if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
            		 //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
            		 //设置字符集
            		 downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(filename.getBytes("UTF-8")) + "?=";
            	 }else{
            		 downloadFileName =  java.net.URLEncoder.encode(filename, "UTF-8");
            	 }
		} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
		}
        return downloadFileName;
	}


	public Book findByBookCord(String bookCode) {
		return bookDAO.findBybookCode(bookCode);
	}


}
